<template>
  <div class="button-select">
    <div class="button-select__list">
      <div
        class="button-select__item"
        :class="{ [selectClass]: isSelected(item) !== false }"
        v-for="(item, index) in options"
        :key="index"
        @click="selectItem(item)"
      >
        {{ getItemLabel(item) }}
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
  name: "ButtonSelect",
  props: {
    modelValue: [Array, String],
    options: {
      type: Array,
      required: true,
    },
    selectClass: {
      type: String,
      default: "text-info",
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    maxSelect: Number,
  },
  data() {
    return {
      selected: [],
    };
  },
  watch: {
    modelValue: {
      handler(val) {
        this.selected = val;
      },
      immediate: true,
    },
  },
  methods: {
    selectItem(item) {
      if (this.multiple) {
        const index = this.isSelected(item);
        if (index === false) {
          this.selected.push(item);
          if (this.maxSelect) {
            const deleteCount = this.selected.length - this.maxSelect;
            if (deleteCount > 0) {
              this.selected.splice(0, deleteCount);
            }
          }
        } else {
          this.selected.splice(index, 1);
        }
      } else {
        this.selected = item;
      }
      this.$emit("input", this.selected);
    },
    getItemLabel(item) {
      if (typeof item === "object") {
        return item.hasOwnProperty("label") ? item.label : item.value;
      }
      return item;
    },
    isSelected(item) {
      if (!this.multiple) {
        return this.selected == item;
      }
      let ret = false;
      this.selected.forEach((element) => {
        const eleVal = element;
        const itemVal = item;
        if (typeof item === "object") {
          eleVal = element.value;
          itemVal = item.value;
        }
        if (eleVal === itemVal) {
          const index = this.selected.indexOf(element);
          ret = index;
        }
      });
      return ret;
    },
  },
});
</script>

<style lang="sass" scoped>
.button-select
    width: 100%
    padding: 0 5px
    position: relative
    overflow-x: auto
    .button-select__list
        display: flex
        .button-select__item
            padding: 0 5px
            white-space: nowrap
.button-select::-webkit-scrollbar
    display: none
</style>
